<?php

class NotificationsController extends AppController {
	
	var $name = 'Notifications';
	var $uses = array('Store');
	var $subject = "";
	var $components = array('Email');
	

	private function _notify($type=null) {
		$this->Email->smtpOptions = array (
			'port' => '26', 
			'timeout' => '30', 
			'host' => 'mail.afha.com.my', 
			'username' => 'admin@afha.com.my', 
			'password' => '1234qwer' );
		/* Set delivery method */
//		$this->Email->delivery = 'smtp';
		$this->Email->delivery = 'debug';
		
		/* Check for SMTP errors. */
		$this->Email->from = 'No-Reply <no-reply@afha.com.my>';
		$this->Email->to = 'Somebody Else <dejagothic@gmail.com>';
		$this->Email->subject = 'Test';
		$this->Email->template = 'monthly';
		$this->Email->sendAs = 'html';
		$this->Email->send();
		$this->set('smtp_errors', $this->Email->smtpError);
	}
	
	public function monthly() {
		
		App::import('Helper', 'Time');
		Configure::write('debug', 2);
		
		
		$time = new TimeHelper();
		$interval = new DateInterval("P1M");
		$to =new DateTime('now');
		$from = new DateTime('now');
		$from->sub($interval);
		
		$filters = array();
		$this->Store->Sale->recursive = -1;
		$filters = '('.$time->daysAsSql($from->format('Y-m-d'),$to->format('Y-m-d'),"Sale.created").')';
		$sales_count = $this->Store->Sale->find('count',array('conditions'=>$filters));
		$available = $this->Store->find('count',array('conditions'=>array('in_store'=>1)));
		$bought = $this->Store->find('count',array('conditions'=>array('Store.date >='=> $from->format('Y-m-d'))));
		$this->set(compact('available'));
		$this->set(compact('sales_count'));
		$this->set(compact('bought'));
		
		$stores = $this->Store->find('all',array('conditions'=>array('Store.modified >='=> $from->format('Y-m-d'))));
		$titles = array();
		foreach($stores as $store) {
			$titles[$store['Store']['id']] = $store['Store']['full_title'];
		}
		$this->Store->Sale->recursive = 3;
		$this->Store->recursive = 0;
		$sales = $this->Store->Sale->find('all',array('conditions'=>array('Sale.created >='=> $from->format('Y-m-d'))));
		$this->set(compact('stores'));
		$this->set(compact('titles'));
		$this->set(compact('sales'));
		
		$this->render('/elements/email/html/monthly');
	}
	
	
}